import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { NavBar, Tabs, Empty, DotLoading, List, PullToRefresh, InfiniteScroll } from 'antd-mobile'
import { useNavigate } from 'react-router-dom'
import axios from '../../api/http'

type ConsultItem = {
  id: string | number
  status: 'consulting' | 'done' | 'closed'
  title?: string
  doctor?: string
  createdAt?: string
}

function Index() {
  const nav = useNavigate()
  const [activeKey, setActiveKey] = useState<'all'|'consulting'|'done'|'closed'>('all')
  const [loading, setLoading] = useState(false)
  const [list, setList] = useState<ConsultItem[]>([])
  const [pageCode, setPageCode] = useState(1)
  const pageSize = 10
  const [hasMore, setHasMore] = useState(true)
  const [refreshing, setRefreshing] = useState(false)

  const currentStatus = useMemo(() => activeKey === 'all' ? undefined : activeKey, [activeKey])

  const fetchPage = useCallback(async (page: number) => {
    const params: any = { pageCode: page, pageSize }
    if (currentStatus) params.status = currentStatus
    const res: any = await axios.get('/consult/list', { params })
    const items: ConsultItem[] = (res && (res.data || res.list)) || []
    return Array.isArray(items) ? items : []
  }, [currentStatus])

  useEffect(() => {
    setLoading(true)
    setHasMore(true)
    setPageCode(1)
    fetchPage(1).then(first => {
      setList(first)
      setHasMore(first.length === pageSize)
    }).finally(() => setLoading(false))
  }, [fetchPage, pageSize])

  const filtered = useMemo(() => {
    return list
  }, [list])

  const loadMore = useCallback(async () => {
    if (!hasMore) return
    const nextPage = pageCode + 1
    const next = await fetchPage(nextPage)
    setList(prev => [...prev, ...next])
    setPageCode(nextPage)
    setHasMore(next.length === pageSize)
  }, [fetchPage, hasMore, pageCode, pageSize])

  const onRefresh = useCallback(async () => {
    setRefreshing(true)
    const fresh = await fetchPage(1)
    setList(fresh)
    setPageCode(1)
    setHasMore(fresh.length === pageSize)
    setRefreshing(false)
  }, [fetchPage, pageSize])

  return (
    <div style={{background:'#fff', minHeight:'100vh'}}>
      <NavBar onBack={() => nav(-1)}>我的问诊记录</NavBar>

      <Tabs activeKey={activeKey} onChange={(k)=>setActiveKey(k as any)}>
        <Tabs.Tab title='全部' key='all' />
        <Tabs.Tab title='咨询中' key='consulting' />
        <Tabs.Tab title='已完成' key='done' />
        <Tabs.Tab title='已关闭' key='closed' />
      </Tabs>

      {loading ? (
        <div style={{display:'flex',alignItems:'center',justifyContent:'center',padding:'40px 0'}}>
          <DotLoading />
          <span style={{marginLeft:8, color:'#999'}}>加载中...</span>
        </div>
      ) : filtered.length === 0 ? (
        <div style={{paddingTop:'14vh'}}>
          <Empty description='暂无订单' />
        </div>
      ) : (
        <PullToRefresh onRefresh={onRefresh} refreshing={refreshing}>
          <div style={{padding:'0 12px'}}>
            {filtered.map(item => (
              <div key={item.id} style={{padding:'12px 0', borderBottom:'1px solid #f2f2f2'}}>
                <div style={{fontSize:15, fontWeight:600}}>{item.title || '问诊单'}</div>
                <div style={{marginTop:6, fontSize:12, color:'#888'}}>
                  {item.doctor || '医生'} · {item.createdAt || ''}
                </div>
              </div>
            ))}
            <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
          </div>
        </PullToRefresh>
      )}
    </div>
  )
}

export default Index
